package com.sdhs.costcontrol.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.sdhs.projectschedule.domain.GcProgressIntegratedConstruction;
import com.sdhs.projectschedule.domain.GcProgressSupply;
import com.sdhs.projectschedule.domain.GcProgressSupplyFill;
import com.sdhs.projectschedule.domain.gcProgressIntegratedConstructionFill;
import com.sdhs.projectschedule.service.IGcProgressIntegratedConstructionService;
import com.sdhs.projectschedule.service.IGcProgressSupplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sdhs.businessfile.domain.BusinessFile;
import com.sdhs.businessfile.service.IBusinessFileService;
import com.sdhs.common.enums.BusinessTypeEnum;
import com.sdhs.common.utils.DateUtils;
import com.sdhs.common.utils.SecurityUtils;
import com.sdhs.costcontrol.domain.GcControlConfirmationPurchase;
import com.sdhs.costcontrol.domain.GcControlConfirmationPurchaseList;
import com.sdhs.costcontrol.domain.GcControlPurchasePlan;
import com.sdhs.costcontrol.mapper.GcControlConfirmationPurchaseListMapper;
import com.sdhs.costcontrol.mapper.GcControlConfirmationPurchaseMapper;
import com.sdhs.costcontrol.mapper.GcControlPurchasePlanMapper;
import com.sdhs.costcontrol.service.IGcControlConfirmationPurchaseService;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 成本控制--采购确认Service业务层处理
 *
 * @author andong
 * @date 2025-03-17
 */
@Service
public class GcControlConfirmationPurchaseServiceImpl implements IGcControlConfirmationPurchaseService
{
    @Autowired
    private GcControlConfirmationPurchaseMapper gcControlConfirmationPurchaseMapper;

    @Autowired
    private GcControlConfirmationPurchaseListMapper gcControlConfirmationPurchaseListMapper;

    @Autowired
    private GcControlPurchasePlanMapper gcControlPurchasePlanMapper;

    @Autowired
    private IBusinessFileService businessFileService;
    @Autowired
    private IGcProgressSupplyService gcProgressSupplyService;
    @Autowired
    private IGcProgressIntegratedConstructionService gcProgressIntegratedConstructionService;
    /**
     * 查询成本控制--采购确认
     *
     * @param id 成本控制--采购确认主键
     * @return 成本控制--采购确认
     */
    @Override
    public GcControlConfirmationPurchase selectGcControlConfirmationPurchaseById(Long id)
    {
        GcControlConfirmationPurchase gcControlConfirmationPurchase = gcControlConfirmationPurchaseMapper.selectGcControlConfirmationPurchaseById(id);
        List<BusinessFile> businessFiles = businessFileService.listByBusinessTypeAndId(BusinessTypeEnum.GC_CONTROL_CONFIRMATION_PURCHASE.getCode(), String.valueOf(id));
        gcControlConfirmationPurchase.setFileList(businessFiles);
        /*获取采购确认的采购计划数据*/
        GcControlPurchasePlan gcControlPurchasePlan = gcControlPurchasePlanMapper.selectGcControlPurchasePlanById(gcControlConfirmationPurchase.getPlanId());
        gcControlConfirmationPurchase.setPurchasePlanName(gcControlPurchasePlan.getPurchasePlanName());
        gcControlConfirmationPurchase.setProcurementType(gcControlPurchasePlan.getProcurementType());
        gcControlConfirmationPurchase.setRemark(gcControlPurchasePlan.getRemark());
        gcControlConfirmationPurchase.setProjectName(gcControlPurchasePlan.getProjectName());
        /*将采购确认列表放进集合中*/
        List<GcControlConfirmationPurchaseList> gcControlConfirmationPurchaseLists = gcControlConfirmationPurchaseListMapper.selectGcPurchaseListByPurchaseId(id);
        gcControlConfirmationPurchase.setGcControlPlanList(gcControlConfirmationPurchaseLists);
        return  gcControlConfirmationPurchase;
    }

    /**
     * 查询成本控制--采购确认列表
     *
     * @param gcControlConfirmationPurchase 成本控制--采购确认
     * @return 成本控制--采购确认
     */
    @Override
    public List<GcControlConfirmationPurchase> selectGcControlConfirmationPurchaseList(GcControlConfirmationPurchase gcControlConfirmationPurchase)
    {
        return gcControlConfirmationPurchaseMapper.selectGcControlConfirmationPurchaseList(gcControlConfirmationPurchase);
    }

    /**
     * 新增成本控制--采购确认
     *
     * @param gcControlConfirmationPurchase 成本控制--采购确认
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertGcControlConfirmationPurchase(GcControlConfirmationPurchase gcControlConfirmationPurchase)
    {
        GcControlConfirmationPurchase gcControlConfirmat = new GcControlConfirmationPurchase();
        gcControlConfirmat.setCreater(SecurityUtils.getUsername());
        gcControlConfirmat.setCreateTime(DateUtils.getNowDate());
        gcControlConfirmat.setPlanId(gcControlConfirmationPurchase.getId());
        List<GcControlConfirmationPurchaseList> gcControlPlanList1 = gcControlConfirmationPurchase.getGcControlPlanList();
        // 初始化总和
        BigDecimal totalAmountPayment = BigDecimal.ZERO;

        if (gcControlPlanList1 != null) {
            for (GcControlConfirmationPurchaseList item : gcControlPlanList1) {
                if (item.getTotalAmount()==null){
                    continue;
                }
                totalAmountPayment = totalAmountPayment.add(item.getTotalAmount());
            }
        }
        // 设置总金额
        gcControlConfirmat.setAmountPayment(totalAmountPayment);
        gcControlConfirmat.setGcControlPlanList(gcControlConfirmationPurchase.getGcControlPlanList());
        gcControlConfirmat.setFileList(gcControlConfirmationPurchase.getFileList());
        gcControlConfirmat.setProcurementType(gcControlConfirmationPurchase.getProcurementType());
        int i = gcControlConfirmationPurchaseMapper.insertGcControlConfirmationPurchase(gcControlConfirmat);
        handler(gcControlConfirmat.getId(),gcControlConfirmat);
        return i;
    }

    /**
     * 修改成本控制--采购确认,没有修改
     *
     * @param gcControlConfirmationPurchase 成本控制--采购确认
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateGcControlConfirmationPurchase(GcControlConfirmationPurchase gcControlConfirmationPurchase)
    {
        GcControlConfirmationPurchase gcControlConfirmat = new GcControlConfirmationPurchase();
        gcControlConfirmat.setCreater(SecurityUtils.getUsername());
        gcControlConfirmat.setCreateTime(DateUtils.getNowDate());
        gcControlConfirmat.setPlanId(gcControlConfirmationPurchase.getPlanId());
        gcControlConfirmat.setId(gcControlConfirmationPurchase.getId());
        List<GcControlConfirmationPurchaseList> gcControlPlanList1 = gcControlConfirmationPurchase.getGcControlPlanList();
        // 初始化总和
        BigDecimal totalAmountPayment = BigDecimal.ZERO;

        if (gcControlPlanList1 != null) {
            for (GcControlConfirmationPurchaseList item : gcControlPlanList1) {
                if (item.getTotalAmount()==null){
                    continue;
                }
                totalAmountPayment = totalAmountPayment.add(item.getTotalAmount());
            }
        }
        // 设置总金额
        gcControlConfirmat.setAmountPayment(totalAmountPayment);
        gcControlConfirmat.setGcControlPlanList(gcControlConfirmationPurchase.getGcControlPlanList());
        gcControlConfirmat.setFileList(gcControlConfirmationPurchase.getFileList());
        gcControlConfirmat.setProcurementType(gcControlConfirmationPurchase.getProcurementType());
        int i = gcControlConfirmationPurchaseMapper.updateGcControlConfirmationPurchase(gcControlConfirmat);
        handler(gcControlConfirmat.getId(),gcControlConfirmat);
        return i;
    }

    /**
     * 批量删除成本控制--采购确认
     *
     * @param ids 需要删除的成本控制--采购确认主键
     * @return 结果
     */
    @Override
    public int deleteGcControlConfirmationPurchaseByIds(Long[] ids)
    {
        return gcControlConfirmationPurchaseMapper.deleteGcControlConfirmationPurchaseByIds(ids);
    }

    /**
     * 删除成本控制--采购确认信息
     *
     * @param id 成本控制--采购确认主键
     * @return 结果
     */
    @Override
    public int deleteGcControlConfirmationPurchaseById(Long id)
    {
        return gcControlConfirmationPurchaseMapper.deleteGcControlConfirmationPurchaseById(id);
    }

    /**
     * 保存采购确认清单数据
     * 1-清单管理
     */
    public void handler(Long id, GcControlConfirmationPurchase gcControlConfirmationPurchase) {
        List<GcControlConfirmationPurchaseList> gcControlConfirmationPurchaseList = gcControlConfirmationPurchase.getGcControlPlanList();
        List<GcControlConfirmationPurchaseList> gcControlConfirmationLists = gcControlConfirmationPurchaseListMapper.selectGcPurchaseListByPurchaseId(id);
        if(CollectionUtil.isNotEmpty(gcControlConfirmationLists)){
            gcControlConfirmationPurchaseListMapper.deletePurchaseListByIds(gcControlConfirmationPurchase.getId());
        }
        /*判断采购类型是否是货物类 0 */
        if(gcControlConfirmationPurchase.getProcurementType().equals("0")) {
            // 初始化 supplyFillList
            List<GcProgressSupplyFill> supplyFillList = new ArrayList<>();
            GcProgressSupply gcProgressSupply = new GcProgressSupply();
            gcProgressSupply.setDeliveryTime(new Date());
            gcProgressSupply.setProjectId(gcControlConfirmationPurchaseList.get(0).getProjectId());
            // 遍历并赋值
            for (GcControlConfirmationPurchaseList purchaseItem : gcControlConfirmationPurchaseList) {
                if (purchaseItem != null) {
                    // 处理可能为 null 的 arrivalQuantity
                    //将到货数量赋值为填报数量
                    BigDecimal arrivalQuantity = purchaseItem.getArrivalQuantity();
                    if (arrivalQuantity == null || arrivalQuantity.compareTo(BigDecimal.ZERO) == 0) {
                        continue; // 跳过当前循环迭代
                    }
                    GcProgressSupplyFill supplyFill = new GcProgressSupplyFill();

                    supplyFill.setSupplyQuantity(arrivalQuantity.longValue());
                    supplyFill.setManageId(purchaseItem.getManageId());
                    supplyFill.setProjectId(purchaseItem.getProjectId());
                    supplyFill.setProcurementType(purchaseItem.getProcurementType());
                    supplyFill.setQuantity(purchaseItem.getQuantity());
                    supplyFillList.add(supplyFill);
                }
            }
            // 循环外设置 supplyFillList
            gcProgressSupply.setSupplyFillList(supplyFillList);
            gcProgressSupplyService.insertGcProgressSupply(gcProgressSupply);
        }else if (gcControlConfirmationPurchase.getProcurementType().equals("1")){
            /**判断采购类型是否是施工类 1 */
            // 初始化 gcProgressIntegratedConstructionFill
            List<gcProgressIntegratedConstructionFill> supplyFillList = new ArrayList<>();
            GcProgressIntegratedConstruction gcProgressSupply = new GcProgressIntegratedConstruction();
            gcProgressSupply.setFillingTime(new Date());
            gcProgressSupply.setProjectId(gcControlConfirmationPurchaseList.get(0).getProjectId());
            // 遍历并赋值
            for (GcControlConfirmationPurchaseList purchaseItem : gcControlConfirmationPurchaseList) {
                if (purchaseItem != null) {
                    /*将到货数量赋值为填报数量*/
                    BigDecimal arrivalQuantity = purchaseItem.getArrivalQuantity();
                    if (arrivalQuantity == null || arrivalQuantity.compareTo(BigDecimal.ZERO) == 0) {
                        continue; // 跳过当前循环迭代
                    }
                    gcProgressIntegratedConstructionFill supplyFill = new gcProgressIntegratedConstructionFill();

                    supplyFill.setSupplyQuantity(arrivalQuantity.longValue());
                    supplyFill.setManageId(purchaseItem.getManageId());
                    supplyFill.setProjectId(purchaseItem.getProjectId());
                    supplyFill.setProcurementType(purchaseItem.getProcurementType());
                    supplyFill.setQuantity(purchaseItem.getQuantity());
                    supplyFillList.add(supplyFill);
                }
            }
            // 循环外设置 supplyFillList
            gcProgressSupply.setSupplyFillList(supplyFillList);
            gcProgressIntegratedConstructionService.insertGcProgressIntegratedConstruction(gcProgressSupply);
        }

        /*清单列表对象*/

        for (int i = 0;i<gcControlConfirmationPurchaseList.size();i++){
            //将到货数量赋值为填报数量
            BigDecimal arrivalQuantity = gcControlConfirmationPurchaseList.get(i).getArrivalQuantity();
            if (arrivalQuantity == null || arrivalQuantity.compareTo(BigDecimal.ZERO) == 0) {
                continue; // 跳过当前循环迭代
            }
            GcControlConfirmationPurchaseList gcConfirmationPurchaseList = gcControlConfirmationPurchaseList.get(i);
            gcConfirmationPurchaseList.setPurchaseId(id);
            gcConfirmationPurchaseList.setId(null);
            gcControlConfirmationPurchaseListMapper.insertGcControlConfirmationPurchaseList(gcConfirmationPurchaseList);
        }

        businessFileService.saveFileBatch(BusinessTypeEnum.GC_CONTROL_CONFIRMATION_PURCHASE.getCode(), String.valueOf(id), gcControlConfirmationPurchase.getFileList());
    }

}
